package com.leetcode.partition6;

import com.leetcode.common.TreeNode;

import java.util.LinkedList;

/**
 * @author `RKC`
 * @date 2021/8/18 11:16
 */
public class LC513找树左下角的值 {

    private int maxDepth = Integer.MIN_VALUE;
    private int answer;

    public int findBottomLeftValue(TreeNode root) {
        backtracking(root, 0);
        return answer;
    }

    public static void main(String[] args) {
//        TreeNode r1 = new TreeNode(1, new TreeNode(2, new TreeNode(4), null), new TreeNode(3,
//                new TreeNode(5, new TreeNode(7), null), new TreeNode(6)));
        TreeNode r1 = new TreeNode(1, null, new TreeNode(1));
        System.out.println(new LC513找树左下角的值().findBottomLeftValue(r1));
    }

    private int bfs(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int answer = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.pollFirst();
                if (i == 0) answer = cur.val;
                if (cur.left != null) queue.add(cur.left);
                if (cur.right != null) queue.add(cur.right);
            }
        }
        return answer;
    }

    private void backtracking(TreeNode root, int currentDepth) {
        if (root.left == null && root.right == null) {
            if (maxDepth < currentDepth) {
                //因为是先向左递归，每到最新一层时，只有该层的第一个元素才会进来
                maxDepth = currentDepth;
                answer = root.val;
            }
            return;
        }
        if (root.left != null) backtracking(root.left, currentDepth + 1);
        if (root.right != null) backtracking(root.right, currentDepth + 1);
    }
}
